#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib.request
import urllib.parse
from langdetect import detect
from langdetect import detect_langs

# 当文本过短或模糊时，判断出来的结果会不确定；
# 如果要让结果唯一，添加以下两行：
from langdetect import DetectorFactory
DetectorFactory.seed = 0

# 判断语言种类
#print(detect(str))

# 概率
#print(detect_langs(str))

#支持检测55种语言：
#af, ar, bg, bn, ca, cs, cy, da, de, el, en, es, et, fa, fi,
#fr, gu, he, hi, hr, hu, id, it, ja, kn, ko, lt, lv, mk, ml,
#mr, ne, nl, no, pa, pl, pt, ro, ru, sk, sl, so, sq, sv, sw,
#ta, te, th, tl, tr, uk, ur, vi, zh-cn, zh-tw


def getTranslate(content):
    text = ''
    lang = 'AUTO'
    if '翻译' in content:
        lst = content.split(' ')
        for s in lst:
            if '翻译' in s:
                continue
            text = text + ' ' + s
    elif '什么意思' in content:
        lst = content.split(' ')
        for s in lst:
            if '什么意思' in s:
                continue
            text = text + ' ' + s
    elif '怎么说' in content:
        lst = content.split(' ')
        for s in lst:
            if '怎么说' in s:
                if '英语' in s:
                    lang = 'en'
                elif '法语' in s:
                    lang = 'fr'
                elif '日语' in s:
                    lang = 'jp'
                continue
            text = text + ' ' + s
    else:
        text = content
    text = text.strip()
    #print("翻译:"+text)
    data = {
    'doctype': 'json',
    'type': 'AUTO',
    'i':text
    }
    data_string=urllib.parse.urlencode(data)
    base_url = "http://fanyi.youdao.com/translate"
    new_url=base_url+"?"+data_string
    response=urllib.request.urlopen(new_url)
    result = eval(response.read().decode('utf-8'))
    translate_result = result['translateResult'][0][0]["tgt"]
    #print(translate_result)
    
    return eval('{"原文":"'+text+'","翻译":"'+translate_result+'"}')

#print(getTranslate("你在干什么 这句话是什么意思"))
